<template>
  <div>
    <el-card class="box-card">
      <h2>用户列表</h2>
      <el-input
          v-model="searchName"
          placeholder="请输入用户名"
          style="margin-bottom: 20px;"
      ></el-input>
      <el-button type="primary" @click="searchUser">查询</el-button>
      <el-table :data="users" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column label="角色">
          <template v-slot="scope">
            <span v-if="scope.row.roles && scope.row.roles.length">{{ scope.row.roles.join(', ') }}</span>
            <span v-else>NULL</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="text" @click="authorizeUser(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="users.length === 0" style="text-align: center; margin-top: 20px;">
        没有找到匹配的用户
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchName: '',
      users: [] // 确保初始化为数组
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      // 向服务器请求用户数据
      this.axios.get('/api/user/get')
          .then(response => {
            const result = response.data;
            if (Array.isArray(result.data)) {
              const users = result.data;
              const promises = users.map(user => {
                return this.axios.get(`/api/right/search/${user.username}`)
                    .then(response => {
                      user.roles = response.data.data.map(role => role.name); // 假设 response.data.data 是角色信息数组
                      return user;
                    })
                    .catch(error => {
                      console.error(`Error fetching role for user ${user.id}:`, error);
                      user.roles = []; // 确保 roles 属性存在，即使发生错误
                      return user;
                    });
              });
              Promise.all(promises).then(usersWithRoles => {
                this.users = usersWithRoles;
              });
            } else {
              console.error('Error: Expected an array but got:', result.data);
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    searchUser() {
      this.axios.get(`/api/user/search?name=${this.searchName}`)
          .then(response => {
            const result = response.data;
            if (Array.isArray(result.data)) {
              const users = result.data;
              const promises = users.map(user => {
                return this.axios.get(`/api/right/search/${user.username}`)
                    .then(response => {
                      user.roles = response.data.data.map(role => role.name); // 假设 response.data.data 是角色信息数组
                      return user;
                    })
                    .catch(error => {
                      console.error(`Error fetching role for user ${user.id}:`, error);
                      user.roles = []; // 确保 roles 属性存在，即使发生错误
                      return user;
                    });
              });
              Promise.all(promises).then(usersWithRoles => {
                this.users = usersWithRoles;
              });
            } else {
              this.users = [];
              console.error('Error: Expected an array but got:', result.data);
            }
          })
          .catch(error => {
            this.users = [];
            console.error('Error searching users:', error);
          });
    },
    authorizeUser(user) {
      this.$router.push(`/right/assignRoles/${user.username}`);
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 800px;
}
</style>
